package com.android.aircondition.common;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.AlphaAnimation;

import com.android.aircondition.R;
import com.android.aircondition.activity.HomeActivity;
import com.android.aircondition.constant.AppConstant;
import com.android.aircondition.service.GreeService;
import com.android.aircondition.service.Mode;
import com.android.aircondition.view.ModeChushiView;
import com.android.aircondition.view.ModeSongfengView;
import com.android.aircondition.view.ModeZhilengView;
import com.android.aircondition.view.ModeZhireView;
import com.android.aircondition.view.SubTabModeView;

public class ScoreGestureDetector extends SimpleOnGestureListener{
	
	private static final int SWIPE_MIN_DISTANCE = 20;
	private Mode mode;
	private GreeService service;
	private SubTabModeView tab;
	private boolean dragKey;
	private Activity activity;
	
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			((HomeActivity)activity).resetViews();
			
			dragKey = false;
			
		};
	};
	  
	public ScoreGestureDetector(Activity activity ,SubTabModeView tab) {
		this.activity = activity;
		this.service = new GreeService(activity);
		this.tab  = tab;
	}
	  
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,float velocityY) {
		
		this.mode = this.service.getModePreference();
		float value = e1.getX() - e2.getX();
		
		if(Math.abs(value)>SWIPE_MIN_DISTANCE){ 
			int temp = getFocusedModeIndex();
			int index = value>0?++temp:--temp;
			
			if(index < 0) index = 4;
			if(index > 4) index = 0;
			
			if(!dragKey){
				setFocusedModeIndex(index);
				dragKey  = true;
			}
			
        }  
		
		return super.onFling(e1, e2, velocityX, velocityY);
	}
	
	private int getFocusedModeIndex(){
		
		if(mode.getAuto())     return 0;
		if(mode.getZhileng())  return 1;
		if(mode.getSongfeng()) return 2;
		if(mode.getChushi())   return 3;
		if(mode.getZhire())    return 4;
		
		return 0;
	}
	
	private void setFocusedModeIndex(int index){
		
		int res = R.drawable.mode_auto_bg;
		
		switch (index) {
			case 0:
				mode.setAuto(true);
				break;
			case 1:
				mode.setZhileng(true);
				
				break;
			case 2:
				mode.setSongfeng(true);
				
				break;
			case 3:
				mode.setChushi(true);
				
				break;
			case 4:
				mode.setZhire(true);
				
				break;
		}
		
		service.setModePreference(mode);
		tab.setFocusedMode(mode);
		
		Message msg = new Message();
		msg.what = AppConstant.NO_0;
		mHandler.sendMessageDelayed(msg, 1500);
		
		
	}

}
